package com.hsy.linemoney.modules.auth.fragment;

import android.app.AlertDialog;
import android.app.Dialog;
import android.content.Context;
import android.content.DialogInterface;
import android.os.Bundle;
import android.os.Message;
import android.text.Editable;
import android.text.TextWatcher;
import android.text.method.HideReturnsTransformationMethod;
import android.text.method.PasswordTransformationMethod;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.MotionEvent;
import android.view.View;
import android.view.ViewGroup;
import android.view.WindowManager;
import android.view.inputmethod.InputMethodManager;
import android.widget.AdapterView;
import android.widget.BaseAdapter;
import android.widget.EditText;
import android.widget.LinearLayout;
import android.widget.ListPopupWindow;
import android.widget.TextView;

import com.deparse.dpframe.tools.utils.DPGsonUtil;
import com.deparse.dpframe.tools.utils.DPLogUtil;
import com.hsy.linemoney.R;
import com.hsy.linemoney.apiservice.Callback;
import com.hsy.linemoney.apiservice.CurrencyService;
import com.hsy.linemoney.apiservice.IsTermsOfUseCompleteService;
import com.hsy.linemoney.apiservice.LineMoneyContext;
import com.hsy.linemoney.apiservice.RegistrationService;
import com.hsy.linemoney.apiservice.ServiceTypeService;
import com.hsy.linemoney.beans.User;
import com.hsy.linemoney.common.PasswordSaver;
import com.hsy.linemoney.modules.auth.activity.AgreementActivity;
import com.hsy.linemoney.modules.auth.activity.VerifyEmailActivity;
import com.hsy.linemoney.modules.common.CommonBaseFragment;
import com.hsy.linemoney.modules.main.MainActivity;
import com.hsy.linemoney.utils.CommonUtils;
import com.liferay.mobile.android.auth.Authentication;
import com.liferay.mobile.android.auth.SignInMethod;
import com.liferay.mobile.android.auth.basic.BasicAuthentication;
import com.liferay.mobile.android.callback.typed.JSONObjectCallback;
import com.liferay.mobile.android.service.Session;
import com.liferay.mobile.android.service.SessionImpl;
import com.liferay.mobile.android.v7.user.UserService;

import org.json.JSONObject;

import java.util.Timer;
import java.util.TimerTask;

/**
 * Created by Administrator on 2016/7/6.
 */
public class SignInFragment extends CommonBaseFragment {
    private TextView sign, forget_password;
    private TextView user_msg, password_msg;
    private EditText password_edit, user;
    private boolean isHidden = true;
    private LinearLayout password_image;

    @Override
    protected int getFragmentLayout() {
        return R.layout.fragment_sign_in;
    }

    private Callback<CurrencyService.CurrencyListResult> currencyListResultCallback = new Callback<CurrencyService.CurrencyListResult>() {
        @Override
        public void onSuccess(int what, CurrencyService.CurrencyListResult result) {
            new ServiceTypeService().getServiceTypeList(serviceTypeListResultCallback);
        }

        @Override
        public void onError(int what, int type, String msg, Exception e) {
            new ServiceTypeService().getServiceTypeList(serviceTypeListResultCallback);
        }
    };

    private Callback<ServiceTypeService.ServiceTypeListResult> serviceTypeListResultCallback = new Callback<ServiceTypeService.ServiceTypeListResult>() {
        @Override
        public void onSuccess(int what, ServiceTypeService.ServiceTypeListResult result) {
            pubJumpMsg();
        }

        @Override
        public void onError(int what, int type, String msg, Exception e) {
            pubJumpMsg();
        }
    };

    private void pubJumpMsg() {

        if (LineMoneyContext.isLoggedIn() && !LineMoneyContext.getLoggedUser().getEmailAddressVerified()) {
            DPLogUtil.d("getIsUseComplete onSuccess 200 getIsTermsOfUseAgreed VerifyEmailActivity");
            hideProgressDialog();
            startActivity(VerifyEmailActivity.class);
        } else {
            new IsTermsOfUseCompleteService().getIsUseComplete(user.getText().toString(), new Callback<IsTermsOfUseCompleteService.UseCompleteGson>() {
                @Override
                public void onSuccess(int what, IsTermsOfUseCompleteService.UseCompleteGson result) {
                    DPLogUtil.d("getIsUseComplete onSuccess");
                    if (result.getStatus().getCode() == 200) {
                        DPLogUtil.d("getIsUseComplete onSuccess 200");
                        if (result.getValue().getIsTermsOfUseAgreed()) {
                            DPLogUtil.d("getIsUseComplete onSuccess 200 getIsTermsOfUseAgreed");
//                        if (LineMoneyContext.isLoggedIn() && !LineMoneyContext.getLoggedUser().getEmailAddressVerified()) {
//                            DPLogUtil.d("getIsUseComplete onSuccess 200 getIsTermsOfUseAgreed VerifyEmailActivity");
//                            startActivity(VerifyEmailActivity.class);
//                        } else {
//                            DPLogUtil.d("getIsUseComplete onSuccess 200 getIsTermsOfUseAgreed MainActivity");
                            startActivityWithTaskCleared(MainActivity.class);
//                        }
                        } else {
                            DPLogUtil.d("getIsUseComplete onSuccess 200 getNoIsTermsOfUseAgreed AgreementActivity");
                            startActivity(AgreementActivity.class, user.getText().toString());
                        }
                    } else {
                        DPLogUtil.d("getIsUseComplete onSuccess 500");
                        showToast(result.getStatus().getMessage());
                    }
                    hideProgressDialog();
                }

                @Override
                public void onError(int what, int type, String msg, Exception e) {
                    showToast(e.getMessage());
                    hideProgressDialog();
                }
            });
        }


//        if (LineMoneyContext.isLoggedIn() && !LineMoneyContext.getLoggedUser().getAgreedToTermsOfUse()) {
////            startActivity(AgreementActivity.class);
//        } else if (LineMoneyContext.isLoggedIn() && !LineMoneyContext.getLoggedUser().getEmailAddressVerified()) {
//            startActivity(VerifyEmailActivity.class);
//        } else {
//            startActivityWithTaskCleared(MainActivity.class);
//        }
    }

    protected static String getUsername(Session session) {
        Authentication auth = session.getAuthentication();
        return ((BasicAuthentication) auth).getUsername();
    }

    //    登录
    public void signIn(final Session session, final JSONObjectCallback callback, final SignInMethod method) {

        try {
            long companyId = Long.valueOf(LineMoneyContext.getLiferay_company_id());
            session.setCallback(callback);
            UserService userService = new UserService(session);
            String username = getUsername(session);
            if (method == SignInMethod.EMAIL) {
                userService.getUserByEmailAddress(companyId, username);
            } else if (method == SignInMethod.USER_ID) {
                userService.getUserById(Long.parseLong(username));
            } else {
                userService.getUserByScreenName(companyId, username);
            }
        } catch (Exception e) {
            callback.onFailure(e);
        }

    }

    private void signIn(final Session session, final JSONObjectCallback callback) {
        String e = getUsername(session);
        SignInMethod method = SignInMethod.fromUsername(e);
        signIn(session, callback, method);
    }

    @Override
    protected void initView(View view, Bundle savedInstanceState) {
        sign = F(R.id.sign);
        sign.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                if (checkSignIn()) {
                    showProgressDialog(getAttchedActivity());
                    final Session session = new SessionImpl(LineMoneyContext.getServer(), new BasicAuthentication(user.getText().toString(), password_edit.getText().toString()));
                    signIn(session, new JSONObjectCallback() {
                        @Override
                        public void onSuccess(JSONObject result) {
                            Log.d("LineMoney", result.toString());
                            session.setCallback(null);
                            LineMoneyContext.setSession(session);
                            LineMoneyContext.setPassword(password_edit.getText().toString());
                            User user = DPGsonUtil.fromJson(result.toString(), User.class);
                            LineMoneyContext.setLoggedUser(user);

                            new CurrencyService().getCurrency(currencyListResultCallback);
                        }

                        @Override
                        public void onFailure(Exception e) {
                            e.printStackTrace();
//                        showToast(R.string.txt_login_failed);
                            showToast(e.getMessage());
                            session.setCallback(null);
                            hideProgressDialog();
                        }
                    });
                }
            }
        });

        forget_password = F(R.id.forget_password);

        user_msg = F(R.id.user_msg);
        password_msg = F(R.id.password_msg);

        forget_password.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                showDialog();
            }
        });

        user = F(R.id.user);
        password_edit = F(R.id.password_edit);

        password_image = F(R.id.password_image);
        password_image.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                if (isEmpty(password_edit.getText().toString())) {
                    return;
                }

                if (isHidden) {
                    password_edit.setTransformationMethod(HideReturnsTransformationMethod.getInstance());
                } else {
                    password_edit.setTransformationMethod(PasswordTransformationMethod.getInstance());
                }
                isHidden = !isHidden;

            }
        });

        if (PasswordSaver.isEnabled()) {
            user.setOnLongClickListener(new View.OnLongClickListener() {
                @Override
                public boolean onLongClick(View v) {
                    final String[] userNameList = PasswordSaver.getUserNameList();
                    if (!isEmpty(userNameList)) {
//                            new AlertDialog.Builder(getAttchedActivity()).setItems(userNameList, new DialogInterface.OnClickListener() {
//                                @Override
//                                public void onClick(DialogInterface dialog, int which) {
//                                    user.setText(userNameList[which]);
//                                    password_edit.setText(PasswordSaver.getPassword(userNameList[which]));
//                                }
//                            }).show();
                        final ListPopupWindow window = new ListPopupWindow(getAttchedActivity());
                        window.setAdapter(new BaseAdapter() {
                            @Override
                            public int getCount() {
                                return userNameList.length;
                            }

                            @Override
                            public Object getItem(int position) {
                                return userNameList[position];
                            }

                            @Override
                            public long getItemId(int position) {
                                return position;
                            }

                            @Override
                            public View getView(int position, View convertView, ViewGroup parent) {
                                TextView textView = new TextView(getAttchedActivity());
                                textView.setText(userNameList[position]);
                                textView.setPadding(0, 10, 0, 10);
                                return textView;
                            }
                        });
                        window.setModal(false);
                        window.setContentWidth(user.getWidth());
                        window.setWidth(user.getWidth());
                        window.setAnchorView(user);
                        window.setOnItemClickListener(new AdapterView.OnItemClickListener() {
                            @Override
                            public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
                                user.setText(userNameList[position]);
                                password_edit.setText(PasswordSaver.getPassword(userNameList[position]));
                                window.dismiss();
                            }
                        });
                        window.show();
                    }
                    return false;
                }
            });
        }

        user.addTextChangedListener(new TextWatcher() {
            @Override
            public void beforeTextChanged(CharSequence s, int start, int count, int after) {

            }

            @Override
            public void onTextChanged(CharSequence s, int start, int before, int count) {

            }

            @Override
            public void afterTextChanged(Editable s) {

//                checkEdit(user, user_line, 0);

                if (user.getText().toString().equals("")) {
                    user_msg.setVisibility(View.GONE);
                }
            }
        });
        password_edit.addTextChangedListener(new TextWatcher() {
            @Override
            public void beforeTextChanged(CharSequence s, int start, int count, int after) {

            }

            @Override
            public void onTextChanged(CharSequence s, int start, int before, int count) {

            }

            @Override
            public void afterTextChanged(Editable s) {

                if (password_edit.getText().toString().equals("")) {
                    password_msg.setVisibility(View.GONE);
                }
            }
        });

    }

    private boolean checkSignIn() {
        if (isEmpty(user.getText().toString())) {
            showToast(R.string.base_login_sign_in_user_name_hint);
            return false;
        } else if (isEmpty(password_edit.getText().toString())) {
            showToast(R.string.base_login_sign_in_password_hint);
            return false;
        }

        PasswordSaver.save(user.getText().toString(), password_edit.getText().toString());

        return true;
    }

    private void showDialog() {

        final Dialog dialog = new AlertDialog.Builder(getAttchedActivity()).create();

        dialog.setCancelable(true);
        dialog.show();
        LayoutInflater inflater = LayoutInflater.from(getAttchedActivity());
        View dialogView = inflater.inflate(R.layout.dialog_forget_password, null);
        dialog.getWindow().setContentView(dialogView);
        dialog.getWindow().clearFlags(WindowManager.LayoutParams.FLAG_ALT_FOCUSABLE_IM);
        final EditText email_edit = (EditText) dialogView.findViewById(R.id.email_edit);
        LinearLayout cancel_linear = (LinearLayout) dialogView.findViewById(R.id.cancel_linear);
//        showKeyboard(email_edit);
        Timer timer = new Timer();
        timer.schedule(new TimerTask() {

            @Override
            public void run() {
                showKeyboard(email_edit);
            }
        }, 200);
        cancel_linear.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                if (dialog != null && dialog.isShowing()) {
                    dialog.dismiss();
                }
            }
        });
        dialogView.findViewById(R.id.sign).setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                RegistrationService service = new RegistrationService();
                service.sendPassword(email_edit.getText().toString(), new Callback<RegistrationService.SendPasswordResult>() {
                    @Override
                    public void onSuccess(int what, RegistrationService.SendPasswordResult result) {
                        showToast(R.string.txt_pass_sent);
                    }

                    @Override
                    public void onError(int what, int type, String msg, Exception e) {
                        showToast(R.string.txt_pass_sent_err);
                    }
                });
            }
        });
    }

    public void showKeyboard(EditText editText) {
        if (editText != null) {
            //设置可获得焦点
            editText.setFocusable(true);
            editText.setFocusableInTouchMode(true);
            //请求获得焦点
            editText.requestFocus();
            //调用系统输入法
            InputMethodManager inputManager = (InputMethodManager) editText
                    .getContext().getSystemService(Context.INPUT_METHOD_SERVICE);
            inputManager.showSoftInput(editText, 0);
        }
    }

    @Override
    protected void initData() {

    }

    @Override
    protected void onHandleMessage(Message msg) {

    }

    @Override
    public void onFragmentUpdate() {

    }
}
